import importlib.util
import json
import os
from typing import Dict, Any

from fastapi import Body
from fastapi import Response, Request, APIRouter
from starlette.templating import Jinja2Templates

from model.result import Result


def dynamic_call(file_path, function_name, *args, **kwargs):
    """
    更简洁的动态调用方法
    """
    # 规范化路径
    file_path = os.path.abspath(file_path)

    # 创建模块规范
    spec = importlib.util.spec_from_file_location("dynamic_module", file_path)
    if spec is None:
        raise ImportError(f"Cannot load module from {file_path}")

    # 创建模块
    module = importlib.util.module_from_spec(spec)

    # 执行模块
    spec.loader.exec_module(module)

    # 获取并调用方法
    if hasattr(module, function_name):
        func = getattr(module, function_name)
        if callable(func):
            return func(*args, **kwargs)
        else:
            raise AttributeError(f"'{function_name}' is not callable")
    else:
        raise AttributeError(f"Method '{function_name}' not found")


templates = Jinja2Templates(directory="templates")
router = APIRouter()


@router.get("/a")
def micro_pay_balance(request: Request, response: Response, ):
    for plugin in os.listdir('node'):
        with open(f"node/{plugin}/config.json", "r", encoding="utf-8") as f:
            config = json.load(f)
            # print(config)
            if plugin == 'node1':
                # print(config[0])
                print(config[0]['target_handler'])
                dynamic_call(f"node/{plugin}/{config[0]['target_handler']}", "main", '111', '1.txt')
    return templates.TemplateResponse("test.html", {'request': request, 'a': os.listdir('node')})


@router.post("/start")
def start(request: Request, body: Dict[str, Any] = Body(...)):
    connections = body.get('connections')
    rectangles = body.get('rectangles')
    for connection in connections:
        print(f'来自于,{connection["from"]}')
        print(f'连接到,{connection["to"]}')
    for rectangle in rectangles:
        print(f'{rectangle}')
    config = body['node_groups'][1]['config']
    dynamic_call(f"node/node1/{body['node_groups'][0]['config'][0]['target_handler']}", "main",
                 body['node_groups'][1]['config'][0]['items'][0]['result'], '1.txt')
    return Result(data=body)


@router.post("/nodes")
def nodes():
    _nodes = []
    for plugin in os.listdir('node'):
        with open(f"node/{plugin}/config.json", "r", encoding="utf-8") as f:
            config = json.load(f)
            _nodes.append({"node_group": plugin, "name": [c['name'] for c in config], "config": config})
            # if plugin == 'node1':
            #     print(config[0]['target_handler'])
            #     dynamic_call(f"node/{plugin}/{config[0]['target_handler']}", "main", '111', '1.txt')
    return Result(data=_nodes)
